﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace FoundationLib.Web.Converters
{
	/// <summary>
	/// This class is a converter stripping HTML tags from string input values.
	/// </summary>
	public class StripHtmlConverter : IConverter
	{
		/// <summary>
		/// Creates a new <see cref="StripHtmlConverter"/>.
		/// </summary>
		public StripHtmlConverter()
		{
		}

		/// <see cref="IConverter.SupportsOptions"/>
		public bool SupportsOptions
		{
			get
			{
				return false;
			}
		}

		/// <see cref="IConverter.Options"/>
		public object Options
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		/// <see cref="IConverter.Convert(object, ConversionDirection)"/>
		public object Convert(object input, ConversionDirection direction)
		{
			//Conversion direction is ignored
			if (!(input is String))
				throw new ArgumentException("Input value is not a string.", "input");

			string inputString = input as String;

			if (inputString == null)
				return null;
			if (inputString == String.Empty)
				return String.Empty;

			string regexString = @"<(.|\n)*?>";
			Regex regex = new Regex(regexString);

			return (regex.Replace(inputString, String.Empty));
		}

		/// <see cref="IConverter.TryConvert(object, ConversionDirection, object)"/>
		public bool TryConvert(object input, ConversionDirection direction, out object output)
		{
			try
			{
				output = this.Convert(input, direction);
				return true;
			}
			catch (Exception)
			{
				output = null;
				return false;
			}
		}
	}
}
